import { Injectable } from '@nestjs/common';
import { BizFailedException } from "@/common/biz-failed/biz-failed.exception";
import { BizFailedCodeEnum } from "@/common/biz-failed/biz-failed.enum";
import { HttpClientService } from "@/common/http-client/http-client.service";

@Injectable()
export class WxService {
  private readonly wxAppId: string = 'wx946ebb3266cec249';
  private readonly wxSecretKey: string = '361300f59e4b8c48d4eebb4a83f2ecbf';
  constructor(
    private readonly httpService: HttpClientService,
  ) {}

  async userLogin(js_code: string): Promise<{openid: string,sessionKey: string}> {
    const params = {
      appid: this.wxAppId,
      secret: this.wxSecretKey,
      js_code,
      grant_type: 'authorization_code',
    };
    const response = await this.httpService
      .request<{
        errcode: number;
        openid: string;
        session_key: string;
      }>( {
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        params,
      })
    const res = response!.data;
    if(res.errcode && res.errcode !== 0){
      throw new BizFailedException(BizFailedCodeEnum.WX_LOGIN_FAILED);
    }
    return {
      openid: res.openid,
      sessionKey: res.session_key,
    };
  }

  /*// 解密敏感数据
  decryptData(encryptedData: string, iv: string, sessionKey: string): {phoneNumber:string}{
    // base64 decode
    const decodeSessionKey = Buffer.from(sessionKey, 'base64');
    const decodeEncryptedData = Buffer.from(encryptedData, 'base64');
    const decodeIv = Buffer.from(iv, 'base64');
    // 解密
    const decipher = createDecipheriv('aes-128-cbc', decodeSessionKey, decodeIv);
    // 设置自动 padding 为 true，删除填充补位
    decipher.setAutoPadding(true);
    let decoded = decipher.update(decodeEncryptedData, 'binary', 'utf8');
    decoded += decipher.final('utf8');
    return JSON.parse(decoded);
  }*/
}
